package freespiritsocial.io.user.data.model.bean

import android.os.Parcelable
import androidx.appcompat.content.res.AppCompatResources
import freespiritsocial.io.user.R
import freespiritsocial.io.user.ext.getTimeFormat
import freespiritsocial.io.user.ext.str
import freespiritsocial.io.user.util.CacheUtil
import kotlinx.android.parcel.Parcelize
import me.hgj.jetpackmvvm.base.appContext
import java.io.File
import java.math.RoundingMode


/*
additionalValue	附加值	integer
address	详细地址	string
otherAddress	地点名称其他的地址	string
advertisersId	关联的广告商ID(有值则是广告贴)	integer
caption	说明	string
city	城市	string
"commentAvatars": [],评论头像列表
"commentCount": 评论数	,
"commentUserName": "", 第一个评论者的昵称
commentCount	评论数	integer
country	国家	string
coverUrl	封面图	string
createTime	创建时间	integer
fileType	1.视频 2.图片	integer
fileUrl	视频或者图片文件路径，多个用逗号隔开	string
invitationId	帖子id	integer
isLike	是否点赞	boolean
isSave	是否保存帖子	boolean
latitude	纬度	number
likeCount	点赞数	integer
locationName	完整地址	string
longitude	经度	number
street	街道	string
tagName	标签名称，多个用逗号隔开	string
town	城镇	string
updateTime	更新时间	integer
userAvatar	发布者用户头像	string
userId	发布者用户id	string
userName	发布者用户姓名	string
 */
@Parcelize
data class PostPojo(
    var address: String? = null,
    val otherAddress: String? = null,
    val advertisersId: Long? = null,
    var caption: String? = null,
    var commentAvatars: List<String>? = null,
    var commentUserName: String? = null,
    var city: String? = null,
    val commentCount: Int = 0,
    var country: String? = null,
    var coverUrl: String? = null,
    val createTime: Long = 0,
    val publishTime: Long? = null,
    var fileType: Int = 0,
    val type: Int = 0,
    var fileUrl: String? = null,
    val invitationId: Long = 0,
    var isLike: Boolean? = null,
    var isSave: Boolean? = null,
    var isFollow: Boolean? = null,
    val latitude: Double = 0.0,
    var likeCount: Int = 0,
    var locationName: String? = null,
    val longitude: Double = 0.0,
    var street: String? = null,
    var tagName: String? = "",
    var town: String? = null,
    val updateTime: Int = 0,
    val userAvatar: String? = null,
    val userId: String? = null,
    val userName: String? = null,
    var venueCategoryLabel: String? = null,
    //本地用
    var localCover: String? = null,
    var uploadFiles: List<File>? = null
): Parcelable {

    var saveFlag = false
    val isVideo get() = fileType == 1 || type == 1
    val fileList get() = fileUrl?.split(",")?.filter { it.isNotEmpty() }?.toMutableList() ?: mutableListOf()
    val likeIcon get() = AppCompatResources.getDrawable(appContext,if (isLike == true) R.mipmap.icon_like_red else R.mipmap.icon_post_like)
    val likeCountStr: String
        get() = likeCount.formatCountToStr()
    val commentCountStr: String
        get() = commentCount.formatCountToStr()
    val pushTime: String
        get() {
            val offsetTime = System.currentTimeMillis().div(1000L) - (publishTime ?: createTime)
            return offsetTime.getFreeSpiritTime((publishTime ?: createTime))
        }
    val followStr
        get() = (if (isFollow == true) R.string.following else R.string.follow).str()

    val tagList
        get() = (tagName ?: "").split(",").let {
            it.filterIndexed { index,s ->
                (index == it.lastIndex) || s.isNotEmpty()
            }
        }
    val isEdit get() = invitationId != 0L

    val isMine get() = CacheUtil.getUser()?.let { it.userId == userId }

    fun formatAddress(): String = StringBuilder().let {
        if (!street.isNullOrEmpty()) it.append(street).append(", ")
        if (!town.isNullOrEmpty()) it.append(town).append(", ")
        if (!city.isNullOrEmpty()) it.append(city)
        it.toString()
    }

    fun clearAddress() {
        address = null
        locationName = null
        street = null
        town = null
        city = null
        country = null
    }

    fun Int.formatCountToStr(): String =
        when {
            this > 999 -> "${this.div(1000f).toBigDecimal().setScale(1,RoundingMode.HALF_UP)}k"
            this > 99999 -> "${this.div(1000_000f).toBigDecimal().setScale(1,RoundingMode.HALF_UP)}w"
            else -> this.toString()
        }

    fun addTag(tag: String) {
        tagName = if (tagName.isNullOrEmpty()) {
            tag
        } else {
            "$tagName,$tag"
        }
    }

    fun canUpload(): Boolean {
        return locationName.isNullOrEmpty().not().and(caption.isNullOrEmpty().not()).and(localCover.isNullOrEmpty().not())
    }

    fun isMyPost(): Boolean {
        val user = CacheUtil.getUser()
        return user?.userId == userId
    }
}

fun Long.getFreeSpiritTime(realTime: Long) = when {
    this < 60 -> "1 min ago"
    this < 3600 -> "${this.div(60)} min ago"
    this < 24 * 3600 -> {
        val hour = this.div(3600)
        "$hour hour${if (hour > 1) "s" else ""} ago"
    }
    this < 30 * 24 * 3600 -> {
        val day = this.div(24 * 3600)
        "$day day${if (day > 1) "s" else ""} ago"
    }
    else -> {
        realTime.getTimeFormat("dd/MM/yyyy")
    }
}